import { ref, computed, ComputedRef } from 'vue'
import { useStore } from 'vuex'
interface LoadPrams {
  pageIndex?: number;
  pageSize?: number;
  [key: string]: any;
}
const useLoadMore = (actionName: string, total: ComputedRef<number>, params: LoadPrams = {}, pageSize = 8) => {
  const store = useStore()
  // 当前页
  const pageIndex = ref((params && params.pageIndex) || 0)
  // 如果不用nextIndex, 会导致计算最后一页时因为提前加1了(store.dispatch里面的then),会导致分页最后一页压根无法触发
  const nextIndex = ref((params && params.pageIndex) || 0)
  const requestParams = computed(() => {
    return {
      ...params,
      pageIndex: nextIndex.value,
    }
  })
  // function to trigger load more
  const loadMorePage = () => {
    console.log('loadMorePage', requestParams.value, pageIndex.value)
    pageIndex.value = nextIndex.value
    store.dispatch(actionName, { searchParams: requestParams.value}).then(() => {
      nextIndex.value++
    })
  }
  const isLastPage = computed(() => {
    console.log('lastPage', total.value, pageSize, pageIndex.value);
    return Math.ceil((total.value || 1) / pageSize) === pageIndex.value + 1
  })
  
  return {
    pageIndex,
    loadMorePage,
    isLastPage
  }
}

export default useLoadMore
